package com.mytools.common.pattern.decorator01;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author LJK
 * @description
 * @date 2025/2/12
 */
public class BufferReadInputStream extends InputStream {

    private final byte[]buffer=new byte[8192];
    private int position=-1;
    private int capacity=-1;
    private final FileInputStream fileInputStream;

    public BufferReadInputStream(FileInputStream fileInputStream) {
        this.fileInputStream=fileInputStream;
    }

    @Override
    public int read() throws IOException {
        if(bufferCanRead()){
            return readFromBuffer();
        }
        bufferRefresh();
        if(!bufferCanRead()){
            return -1;
        }
        return readFromBuffer();
    }

    private void bufferRefresh() throws IOException {
        capacity= fileInputStream.read(buffer);
        position=0;
    }

    private int readFromBuffer(){
        return buffer[position++] &0xFF;
    }

    private boolean bufferCanRead() {
        if(capacity==-1||position==capacity)//-1的时候说明buffer填充失败，==的时候说明已经读完了
            return false;
        return true;
    }

    @Override
    public void close() throws IOException {
        super.close();
    }
}
